package cn.wolfcode.luowowo.comment.service.impl;

import cn.wolfcode.luowowo.comment.domain.StrategyComment;
import cn.wolfcode.luowowo.comment.query.StrategyCommentQuery;
import cn.wolfcode.luowowo.comment.repository.IStrategyCommentRepository;
import cn.wolfcode.luowowo.comment.service.IStrategyCommentService;
import com.alibaba.dubbo.config.annotation.Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.List;

@Service
public class StrategyCommentServiceImpl implements IStrategyCommentService {

    @Autowired
    private IStrategyCommentRepository repository;

    @Autowired
    private MongoTemplate template;

    @Override
    public void save(StrategyComment comment) {
        if (!StringUtils.hasLength(comment.getId())) {
            comment.setCreateTime(new Date());
        }
        repository.save(comment);
    }

    @Override
    public Page query(StrategyCommentQuery qo) {
        //repository和template无法直接查询分页数据, 所以需要自己封装
        Query query = new Query();
        //拼接查询条件
        if (qo.getDetailId() != -1) {
            query.addCriteria(Criteria.where("detailId").is(qo.getDetailId()));
        }
        //查总数
        long count = template.count(query, StrategyComment.class);
        if (count == 0) {
            return Page.empty();
        }
        //查询当前页的list
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.DESC, "createTime");
        List<StrategyComment> list = template.find(query, StrategyComment.class);
        return new PageImpl(list, pageable, count);
    }

    @Override
    public void commentThumbUp(String detailId, Long userId) {
        //1. 判断点赞用户id集合中是否有当前登录用户的id
        StrategyComment comment = repository.findById(detailId).get();
        List<Long> thumbuplist = comment.getThumbuplist();
        if (!thumbuplist.contains(userId)) {
            //2. 如果不在集合中,点赞数加一
            comment.setThumbupnum(comment.getThumbupnum() + 1);
            thumbuplist.add(userId);
        }else {
            //3. 如果当前用户存在集合中, 点赞数减一, 移除用户id
            comment.setThumbupnum(comment.getThumbupnum() - 1);
            thumbuplist.remove(userId);
        }
        repository.save(comment);
    }

    @Override
    public List<StrategyComment> queryByUserId(Long id) {
        return repository.findByUserId(id);
    }
}
